# -*- coding: utf-8 -*-

# Crispy Plotter, a fast and easy-to-use function plotter
# Copyright (C) 2010 Konrad Kölzer

# Crispy Plotter is free software, see License.txt for details.

# Crispy Plotter Translation script for Installer and Uninstaller
# Written by Konrad Kölzer

"""
This script will scan the cplotter.nsi for strings to translate between
the line marks BEGIN_STRINGS_TO_TRANSLATE and END_STRINGS_TO_TRANSLATE.
The found strings are then translated to the languages
provided by the gnugettext install.mo files inside the locale folder.
After ranslation, these strings are inserted into cplotter.nsi between
the line marks BEGIN_TRANSLATED_STRINGS and END_TRANSLATED_STRINGS.
"""

fileName = 'cplotter.nsi'
domain = 'install'
supportedLanguages = { \
'de' : 'German', \
'es' : 'Spanish', \
'pt' : 'Portuguese'}

import re
import gettext
import os

def loadInstallScript(filename):
    f = file(filename, 'r')
    lines = f.readlines()
    f.close()
    return lines

def processTranslatableLine(line, strings):
    m = re.match('^\s+(\w+)\s+(\w+)\s+\$\{(\w+)\}\s+\"(.+)\"\s+$', line)
    if m != None:
        typename, varname, lang, value = [m.group(i) for i in range(1, 5)]
        print('Found string %s' % varname)
        if typename == 'LangString':
            strings[varname] = value

def processTranslatableLines(lines):
    parse = False
    strings = dict()
    for line in lines:
        if '### BEGIN_STRINGS_TO_TRANSLATE ###' in line and parse == False:
            parse = True
        elif '### END_STRINGS_TO_TRANSLATE ###' in line and parse:
            parse = False
        elif parse:
            processTranslatableLine(line, strings)
    print('Found %d translatable strings.' % len(strings))
    return strings

def translateStrings(translatedLines, strings, language, languageName):
    global supportedLanguages
    global domain
    print('Translating to %s (%s).' % (languageName, language))
    try:
        lang = gettext.translation(domain, 'locale', languages=[language])
        _ = lang.ugettext
        text = '\tLangString %s ${LANG_%s} "%s"\n'
        translatedLines.append('\t; %s translation strings:\n' % languageName)
        # Add language locale as "translated string"
        line = text % ('LSLanguageCode', languageName.upper(), language)
        translatedLines.append(line.encode('ISO-8859-1'))
        for s in strings:
            trans = _(strings[s]).encode('ISO-8859-1')
            trans = trans.replace(r'"', r'$\"') # Escaping double quotes in NSIS style 
            line = text % (s, languageName.upper(), trans)
            translatedLines.append(line)
    except IOError as ioe:
        print(ioe)       

def translateLanguages(strings):
    translatedLines = []
    for language, languageName in supportedLanguages.iteritems():
        translateStrings(translatedLines, strings, language, languageName)
    return translatedLines

def insertTranslatedLines(lines, translatedLines):
    index = 0
    startIndex = -1
    endIndex = -1
    for line in lines:
        if '### BEGIN_TRANSLATED_STRINGS ###' in line:
            startIndex = index + 1
        elif '### END_TRANSLATED_STRINGS ###' in line and startIndex != -1:
            endIndex = index - 1
            print('Replaced %d old lines with %d new lines starting at line %d.' % \
                  (endIndex - startIndex + 1, len(translatedLines), startIndex + 1, ))
        index += 1
    if startIndex == -1 or endIndex == -1:        
        if startIndex == -1:
            exit('Error: Could not find ### BEGIN_TRANSLATED_STRINGS ### mark')
        if endIndex == -1:
            exit('Error: Could not find ### END_TRANSLATED_STRINGS ### mark')
        return lines
    else:
        return lines[:startIndex] + translatedLines + lines[endIndex + 1:]
    
def writeTranslatedFile(lines, newLines):
    global fileName
    backupFileName = fileName + '.bak'
    counter = 0
    while os.path.exists(backupFileName):
        counter += 1
        backupFileName = fileName + '.' + str(counter) + '.bak'
    os.rename(fileName, backupFileName)
    print('Created backup file %s of current %s.' % (backupFileName, fileName))
    f = file(fileName, 'w')
    f.writelines(newLines)
    f.close()
    print('New file %s written.' % fileName)
            
lines = loadInstallScript(fileName)
strings = processTranslatableLines(lines)
if len(strings) > 0:  
    translatedLines = translateLanguages(strings)
    newLines = insertTranslatedLines(lines, translatedLines)
    writeTranslatedFile(lines, newLines)
else:
    print('Error: No translatable strings found.')
